package com.woniu.liuzhougov.authorityControl.service.impl;

import com.woniu.liuzhougov.authorityControl.dao.UserRoleMapper;
import com.woniu.liuzhougov.authorityControl.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhuxinpan
 * @version 1.0
 * @className UserRoleServiceImpl
 * @description
 * @date 2019/4/28 18:16
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * @param userId
     * @return java.util.List<java.lang.Integer>
     * @author zhuxinpan
     * @date 2019/4/28 18:15
     * @description 列出用户拥有的角色
     */
    @Override
    public List<Integer> listRoleIdByUserId(Integer userId) {
        return userRoleMapper.listRoleIdByUserId(userId);
    }

    /**
     * @param userId
     * @param roleIds
     * @return int
     * @author zhuxinpan
     * @date 2019/4/28 19:45
     * @description 设置用户角色
     */
    @Override
    @Transactional
    public int setRole(Integer userId, Integer[] roleIds) {
        //修改前的角色集合
        Set<Integer> oldRoleIds = new HashSet<>(listRoleIdByUserId(userId));
        //修改后的角色集合
        Set<Integer> newRoleIds = new HashSet<>(Arrays.asList(roleIds));
        //要移除的角色id集合
        Set<Integer> removeRoleIds = new HashSet<>();
        //先将之前的集合放入,再移除新集合的元素,就是需要删除的集合id
        removeRoleIds.addAll(oldRoleIds);
        removeRoleIds.removeAll(newRoleIds);
        //要添加的角色id集合
        //与上面相反的思路
        Set<Integer> addRoleIds = new HashSet<>();
        addRoleIds.addAll(newRoleIds);
        addRoleIds.removeAll(oldRoleIds);
        int result = 0;
        if (removeRoleIds.size() > 0) {
            result += userRoleMapper.deleteByUserId(userId, removeRoleIds);
        }
        if (addRoleIds.size() > 0) {
            result += userRoleMapper.insertByUserId(userId, addRoleIds);
        }
        return result;
    }

    /**
     * @param roleId
     * @return int
     * @author zhuxinpan
     * @date 2019/4/28 20:25
     * @description 统计角色使用次数
     */
    @Override
    public int countRecordByRoleId(Integer roleId) {
        return userRoleMapper.countRecordByRoleId(roleId);
    }

}
